const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const PluginPath = './';

class H265webjsPlugin {
    constructor() {
        this.scripts = [
            path.join(PluginPath, 'missile.js'),
            path.join(PluginPath, 'h265webjs-v20221106.js'),
        ];
    }
    apply(compiler) {

        const copyPlugin = new CopyWebpackPlugin({
            patterns: [
                { from: path.resolve(__dirname, './h265web/missile.js'), to: PluginPath },
                { from: path.resolve(__dirname, './h265web/h265webjs-v20221106.js'), to: PluginPath },
                { from: path.resolve(__dirname, './h265web/missile-v20221120.wasm'), to: PluginPath },
            ]
        });
        copyPlugin.apply(compiler);

        compiler.hooks.compilation.tap('H265webjsPlugin', (compilation) => {


            const compiler = compilation.compiler;
            const HtmlWebpackPlugin = compiler.options.plugins.find(
                (p) => p?.constructor?.name === 'HtmlWebpackPlugin',
            )?.constructor;

            if (!HtmlWebpackPlugin) {
                return undefined;
            }

            if (HtmlWebpackPlugin.version && HtmlWebpackPlugin.version >= 4) {
                HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
                    'H265webjsPlugin',
                    (data, callback) => {
                        this.scripts.forEach((script) => {
                            const scriptTag = `<script src="${script}"></script>`;
                            data.html = data.html.replace('</head>', `${scriptTag}\n</head>`);
                        });
                        callback(null, data)
                    })
            } else {
                compilation.hooks.htmlWebpackPluginBeforeHtmlProcessing.tapAsync(
                    'H265webjsPlugin',
                    (data, callback) => {
                        this.scripts.forEach((script) => {
                            const scriptTag = `<script src="${script}"></script>`;
                            data.html = data.html.replace('</head>', `${scriptTag}\n</head>`);
                        });
                        callback(null, data);
                    }
                );
            }
        });
    }
}


module.exports = H265webjsPlugin;
